package test;

import java.util.Set;
import java.util.TreeSet;

import javax.security.auth.login.LoginException;

import org.xmpp.Connection;
import org.xmpp.TcpConnection;
import org.xmpp.im.Roster.Contact;
import org.xmpp.stanza.Presence;
import org.xmpp.stanza.PresenceEvent;
import org.xmpp.stanza.PresenceListener;

public class GoogleService implements Runnable, GenericService{

	private Set<String> onlineList;
	private Connection connection;
	private String username;
	private String password;
	
	@Override
	public GenericService login(String username, String password) {
		onlineList = new TreeSet<String>();
		this.username = username;
		this.password = password;
		new Thread(this).start();
		return this;
	}
	
	public void run(){
		try{
			connection = new TcpConnection("gmail.com","talk.google.com", 5222);
	    	connection.addPresenceListener(new PresenceListener() {
	    		@Override
	    	    public void handle(PresenceEvent e) {
	    			if( e.getPresence().getFrom() == null )return;
	    			Contact c = connection.getRosterManager().getContact(e.getPresence().getFrom());
	    			String name = c==null?null:c.getName();
	    			if( name != null ){
	    				if (e.isIncoming())
	    					onlineList.add(name);
	    				else
	    					onlineList.remove(name);
	    	        }
	    	    }
	    	});
	    	connection.connect();
	    	try {
	    		connection.login(username, password, "TEST");
	    	}catch (LoginException e) {
				e.printStackTrace();
			}
	    	connection.send(new Presence());
	    	//connection.close();		
		}catch(Exception e){}
	}

	@Override
	public Set<String> getOnlineList() {
		return onlineList;
	}


}
